<template>
  <div class="event-handle">
    <!-- 头部区域 -->
    <van-nav-bar
        title="事件处理"
        left-text="返回"
        left-arrow
        @click-left="goBack"
        fixed
    />

    <!-- 主体内容区 -->
    <div class="content" style="padding-top: 46px;">
      <van-pull-refresh v-model="loading" @refresh="fetchData">
        <div class="event-list">
          <van-cell-group
              v-for="item in eventList"
              :key="item.id"
              :class="{ 'is-handled': item.status === 1 }"
              class="event-item">
            <van-cell>
              <template #icon>
                <van-icon
                    :name="item.tid === 1 ? 'warning-o' : 'video-o'"
                    class="event-icon"
                />
              </template>

              <template #title>
                <div class="event-info" @click="() => goToDetail(item.id)">
                  <div class="event-title">
                    {{ getEventType(item.tid) }}
                  </div>
                  <div class="event-desc">
                    {{ item.address }}出现{{ getEventType(item.tid) }}
                  </div>
                </div>
              </template>

              <template #right-icon>
                <div class="event-meta">
                  <div class="event-time">{{ formatTime(item.startTime) }}</div>
                  <van-button
                      :type="item.status === 0 ? 'warning' : 'success'"
                      size="small"
                      @click.stop="handleEvent(item)">
                    {{ item.status === 0 ? '待处理' : '已处理' }}
                  </van-button>
                </div>
              </template>
            </van-cell>
          </van-cell-group>

          <!-- 空状态 -->
          <van-empty
              v-if="!loading && eventList.length === 0"
              description="暂无报警事件"
          />
        </div>
      </van-pull-refresh>

      <!-- 紧急按钮 -->
      <van-button
          type="danger"
          class="emergency-btn"
          icon="warning-o"
          size="large"
          round
          @click="goadd">
        紧急按钮
      </van-button>
    </div>

    <!-- 添加事件弹窗 -->
    <van-dialog
        v-model:show="dialogFormVisible"
        title="紧急事件"
        show-cancel-button
        :before-close="handleDialogClose"
        @closed="handleDialogClosed">
      <van-form ref="eventForm">
        <!-- 事件类型选择 -->
        <van-field
            v-model="formData.typeName"
            name="事件类型"
            label="事件类型"
            readonly
            placeholder="请选择事件类型"
            @click="showTypePopup = true"
            :rules="[{ required: true, message: '请选择事件类型' }]"
        />

        <!-- 地点选择 -->
        <van-field
            v-model="formData.address"
            name="发生地点"
            label="发生地点"
            readonly
            placeholder="请选择发生地点"
            @click="showAddressPopup = true"
            :rules="[{ required: true, message: '请选择发生地点' }]"
        />
      </van-form>

      <!-- 事件类型选择弹窗 -->
      <van-popup
          v-model:show="showTypePopup"
          position="bottom"
          round
          safe-area-inset-bottom>
        <van-picker
            show-toolbar
            title="选择事件类型"
            :columns="typeList.map(item => ({
              text: item.typename,
              value: item.typeId
            }))"
            @confirm="onTypeConfirm"
            @cancel="showTypePopup = false"
        />
      </van-popup>

      <!-- 地点选择弹窗 -->
      <van-popup
          v-model:show="showAddressPopup"
          position="bottom"
          round
          safe-area-inset-bottom>
        <van-picker
            show-toolbar
            title="选择地点"
            :columns="options.map(item => ({
              text: item.label,
              value: item.label
            }))"
            @confirm="onAddressConfirm"
            @cancel="showAddressPopup = false"
        />
      </van-popup>
    </van-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'EventHandle',

  data() {
    return {
      dialogFormVisible: false,
      showTypePopup: false,
      showAddressPopup: false,
      loading: false,

      // 表单数据
      formData: {
        tid: '',
        typeName: '',
        address: ''
      },

      // 选项数据
      options: [{
        value: '1',
        label: '1F4c'
      }, {
        value: '2',
        label: '2F6c'
      }, {
        value: '3',
        label: '3F7c'
      }],

      typeList: [],
      eventList: []
    }
  },

  methods: {
    // 返回上一页
    goBack() {
      this.$router.go(-1)
    },

    // 打开添加弹窗
    goadd() {
      this.dialogFormVisible = true
      this.resetForm()
    },

    // 处理弹窗关闭
    handleDialogClose(action, done) {
      if (action === 'confirm') {
        this.add().then(() => {
          done()
        }).catch(() => {
          done(false)
        })
      } else {
        this.resetForm()
        done()
      }
    },

    // 弹窗完全关闭后的回调
    handleDialogClosed() {
      this.resetForm()
    },

    // 重置表单
    resetForm() {
      this.formData = {
        tid: '',
        typeName: '',
        address: ''
      }
      this.showTypePopup = false
      this.showAddressPopup = false
      if (this.$refs.eventForm) {
        this.$refs.eventForm.resetValidation()
      }
    },

    // 类型选择确认
    onTypeConfirm(value) {
      this.formData.tid = value.value
      this.formData.typeName = value.text
      this.showTypePopup = false
    },

    // 地点选择确认
    onAddressConfirm(value) {
      this.formData.address = value.text
      this.showAddressPopup = false
    },

    // 添加事件
    async add() {
      try {
        await this.$refs.eventForm.validate()
        const params = {
          tid: this.formData.tid,
          address: this.formData.address
        }
        const res = await axios.post("http://localhost:9999/api-safe-service/detail/add", params)
        this.$toast.success("报备成功")
        this.fetchData()
        return true
      } catch (error) {
        this.$toast.fail(error.message || "提交失败")
        return false
      }
    },

    // 跳转到详情页
    goToDetail(id) {
      this.$router.push({
        path: '/detail',
        query: {id}
      })
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },

    // 处理事件
    handleEvent(item) {
      if (item.status === 0) {
        this.$dialog.confirm({
          title: '提示',
          message: '确认处理此警报?',
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        }).then(() => {
          this.$toast.success('处理成功')
          item.status = 1
        }).catch(() => {
          this.$toast('已取消操作')
        })
      }
    },

    // 获取事件类型
    getEventType(tid) {
      return tid === 1 ? '入侵报警' : '周界报警'
    },

    // 获取数据
    async fetchData() {
      if (this.loading) return

      try {
        this.loading = true
        const res = await axios.post('http://localhost:9999/api-safe-service/detail/findAll')
        if (res.data?.code === 1) {
          this.eventList = res.data.data
        } else {
          throw new Error('获取数据失败')
        }
      } catch (error) {
        this.$toast.fail(error.message || '网络请求失败')
      } finally {
        this.loading = false
      }
    }
  },

  async created() {
    try {
      const res = await axios.post("http://localhost:9999/api-safe-service/type/findAll")
      this.typeList = res.data
    } catch (error) {
      this.$toast.fail('获取事件类型失败')
    }

    this.fetchData()
  }
}
</script>

<style scoped>
.event-handle {
  min-height: 100vh;
  background: #f7f8fa;
}

.content {
  padding-bottom: 80px;
}

.event-list {
  padding: 12px;
}

.emergency-btn {
  position: fixed;
  right: 16px;
  bottom: 80px;
  z-index: 99;
}

.event-item {
  margin-bottom: 12px;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.event-item.is-handled {
  opacity: 0.8;
}

.event-icon {
  font-size: 24px;
  color: #ee0a24;
  margin-right: 12px;
}

.event-info {
  flex: 1;
}

.event-title {
  font-size: 16px;
  font-weight: bold;
  color: #323233;
  margin-bottom: 4px;
}

.event-desc {
  font-size: 14px;
  color: #969799;
}

.event-meta {
  text-align: right;
}

.event-time {
  font-size: 12px;
  color: #969799;
  margin-bottom: 8px;
}

:deep(.van-cell) {
  align-items: flex-start;
  padding: 16px;
}

:deep(.van-button--small) {
  padding: 0 16px;
  height: 28px;
}

:deep(.van-nav-bar) {
  background-color: #fff;
}

:deep(.van-dialog__content) {
  padding: 20px 16px;
}

:deep(.van-picker) {
  width: 100%;
}

:deep(.van-picker-toolbar) {
  background-color: #f7f8fa;
}

:deep(.van-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.van-popup) {
  border-radius: 16px 16px 0 0;
}
</style>